package cn.zjweu.controller;
import cn.zjweu.pojo.Book;
import cn.zjweu.service.BookService;
import cn.zjweu.utils.ResultUtils;
import cn.zjweu.utils.ResultVo;
import cn.zjweu.utils.StatusCode;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/api/v1/book")
public class BookController {
    @Autowired
    private BookService bookService;
    @GetMapping("/list")
    public ResultVo getAllBook() {
        List<Map<String, Object>> all = bookService.getAll();
        return ResultUtils.success("获取成功", StatusCode.SUCCESS_CODE,all);
    }
    @GetMapping("/name")
    public ResultVo getLikeBook(@RequestParam("name") String name){
        List<Map<String, Object>> like = bookService.getLike(name);
        return ResultUtils.success("获取成功",StatusCode.SUCCESS_CODE,like);
    }
    @PostMapping("/addbook")
    public ResultVo addBook(@RequestBody Book book){
        System.out.println(book+"================");
        int i = bookService.addBook(book);
        if (i==1){
            return ResultUtils.error("添加成功",StatusCode.SUCCESS_CODE);
        }else {
            return ResultUtils.error("添加失败",StatusCode.SUCCESS_CODE);
        }
    }
    @PutMapping("/update")
    public ResultVo updateBook(@RequestBody Book book){
        System.out.println(book+"================");
        int i = bookService.updateBook(book);
        if (i==1){
            return ResultUtils.error("更新成功",StatusCode.SUCCESS_CODE);
        }else {
            return ResultUtils.error("更新失败",StatusCode.SUCCESS_CODE);
        }
    }

    @PostMapping("/deleteById")
    public ResultVo deleteBook(@RequestBody Map<String, Integer> map){
        int i = bookService.deleteBook(map.get("id"));
        if (i==1){
            return ResultUtils.error("删除成功",StatusCode.SUCCESS_CODE);
        }else {
            return ResultUtils.error("删除失败",StatusCode.SUCCESS_CODE);
        }
    }
    @GetMapping("/id")
    public ResultVo  getlikeBook(@RequestParam("id") int id){
        List<Map<String, Object>> categoryIdBooks = bookService.getCategoryIdBooks(id);
        return ResultUtils.success("获取成功",StatusCode.SUCCESS_CODE,categoryIdBooks);
    }
    @GetMapping("/bookid")
    public ResultVo getidBook(@RequestParam("id") int id){
        Book idBook = bookService.getIdBook(id);
        return ResultUtils.success("获取成功",StatusCode.SUCCESS_CODE,idBook);
    }
    @PostMapping("/page")
    public ResultVo getPage(@RequestBody PageInfo pageInfo){
        int pageNum = pageInfo.getPageNum();
        int pageSize = pageInfo.getPageSize();
        PageInfo<Map<String, Object>> pageBook = bookService.getPageBook(pageNum, pageSize);
        return ResultUtils.success("获取成功",StatusCode.SUCCESS_CODE,pageBook);
    }

}
